package org.video.mine.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.flexbox.FlexboxLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.Urls;
import org.video.mine.adapter.PlayListAdapter;
import org.video.mine.databinding.ActivityMovieDetailBinding;
import org.video.mine.entity.LoadingEntity;
import org.video.mine.entity.MovieDetailEntity;
import org.video.mine.entity.MoviePlayerEntity;
import org.video.mine.entity.PlayListEntity;
import org.video.mine.event.DownDetailEvent;
import org.video.mine.event.LoadFailedEvent;
import org.video.mine.mycode.DownTask;
import org.video.mine.mycode.DownThread;
import org.video.mine.mycode.ShowMessageDialog;
import org.video.mine.network.JsoupGet;
import org.video.mine.utils.Progress;
import org.video.mine.utils.ScreenUtils;

import java.io.File;
import java.io.Serializable;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MovieDetailActivity extends AppCompatActivity {

    private ActivityMovieDetailBinding binding;
    private String url;
    private MovieDetailEntity movieDetail;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0:
                    progressBar.dismiss();
                    binding.rlReload.setVisibility(View.GONE);
                    binding.llInfo.setVisibility(View.VISIBLE);
                    playListAdapter.notifyDataSetChanged();
                    initView();
                    break;
                case 1:
                    progressBar.dismiss();
                    binding.llInfo.setVisibility(View.GONE);
                    binding.rlReload.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    Toast.makeText(context, (CharSequence) msg.obj,Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private List<MoviePlayerEntity> playerEntities;
    private Context context;
    private Progress progressBar;
    private List<PlayListEntity> playLists = new ArrayList<>();
    private PlayListAdapter playListAdapter;
    private String name="";
    private String imgUrl="";
    private MyPreference preference;

    private void initView() {
        playerEntities = playLists.get(0).getPlayLists();
        binding.setMovieInfo(movieDetail);
        if (movieDetail==null)
            return;
        name = movieDetail.getName();
        if (name.length() > 10) {
            name = name.substring(0, 10);
        }
        imgUrl = movieDetail.getImgUrl();
//        initFlexBox();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_movie_detail);
        setContentView(binding.getRoot());
        context = this;
        Log.d("顺序：","detailCreate");
        EventBus.getDefault().register(this);

        progressBar = new Progress(context);
        intView();
        initClick();
        url = getIntent().getStringExtra("url");
        Log.d("detailUrl",url);

        if (!TextUtils.isEmpty(url)){
            progressBar.show();
            initData();
        }else {
            mHandler.sendEmptyMessage(1);
        }
    }

    private void intView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.ryPlayList.setLayoutManager(layoutManager);
        playListAdapter = new PlayListAdapter(playLists,context);
        binding.ryPlayList.setAdapter(playListAdapter);

        preference = MyPreference.getInstance();
        preference.setPreference(context);
    }

    private void initClick() {
        binding.rlReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(url)){
                    progressBar.show();
                    initData();
                }else {
                    mHandler.sendEmptyMessage(1);
                }
            }
        });

        /*binding.tvDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!playListAdapter.getLoading()) {
                    playListAdapter.setLoading(true);
                    binding.tvDownload.setTextColor(getResources().getColor(R.color.transAccent));
                    binding.tvPlay.setTextColor(getResources().getColor(R.color.gray));
                    playListAdapter.notifyDataSetChanged();
                }
            }
        });*/

        /*binding.tvPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playListAdapter.getLoading()) {
                    playListAdapter.setLoading(false);
                    binding.tvPlay.setTextColor(getResources().getColor(R.color.transAccent));
//                    binding.tvDownload.setTextColor(getResources().getColor(R.color.gray));
                    playListAdapter.notifyDataSetChanged();
                }
            }
        });*/
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                playLists.clear();
                if (Urls.urlHomeType==0) {
                    playLists.addAll(JsoupGet.getMovieDetail(url));
                }else {
                    playLists.addAll(JsoupGet.getMovieDetail2(url));
                }
                if (playLists.size()>0) {
                    movieDetail = (MovieDetailEntity) playLists.get(0).getMovieDetail();
                    mHandler.sendEmptyMessage(0);
                }else {
                    mHandler.sendEmptyMessage(1);
                }
            }
        }).start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("顺序：","detailStart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void downLoad(DownDetailEvent event){
        if (event!=null){
            showMessageDialog(event.pos);
        }
    }

    @Subscribe
    public void loadFailed(LoadFailedEvent event){
        if (event!=null){
            Message message = Message.obtain();
            message.what = 2;
            message.obj = event.msg;
            mHandler.sendMessage(message);
//            Toast.makeText(context, event.msg,Toast.LENGTH_SHORT).show();
        }
    }

    private void showMessageDialog(final int pos){
        final ShowMessageDialog dialog = new ShowMessageDialog(context,true);
        dialog.setTvTitle("请选择下载内容");
        dialog.setRecyView(MovieDetailActivity.this.playLists.get(pos).getPlayLists());
//        dialog.setTvContent("是否下载《"+name+"》全集？");
        dialog.setClickListener(new ShowMessageDialog.ClickListener() {
            @Override
            public void clickPositive(final List<MoviePlayerEntity> playListsLoad) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0;i<playListsLoad.size();i++){
                            MoviePlayerEntity moviePlayerEntity = playListsLoad.get(i);
                            if (DownTask.downThreadList == null) {
                                DownTask.downThreadList = new ArrayList<>();
                            }
                            boolean isHave = false;
                            DownThread downThread = null;
                            for (DownThread thread : DownTask.downThreadList) {
                                if (thread.name.equals(name) && thread.set.equals(moviePlayerEntity.getName())) {
                                    isHave = true;
                                    downThread = thread;
                                    break;
                                }
                            }
                            File loadFile = new File(GlobalStr.getSDPath(context) + name + "/" + moviePlayerEntity.getName() + GlobalStr.saveType);
                            if (!isHave && !loadFile.exists()){
                                String m3u8="";
                                String m3u8Url="";
                                String name="";
                                String movieUrl = moviePlayerEntity.getUrl();
                                String url = movieUrl.startsWith(Urls.getHomeUrl0())?movieUrl:(Urls.getHomeUrl0() +movieUrl);
                                List<List> movieList = JsoupGet.getPanelBody(url);
                                if (movieList.size()==3) {
                                    m3u8 = (String) movieList.get(0).get(0);
                                    name = (String) movieList.get(2).get(0);
                                }
                                if (name.length()>10){
                                    name = name.substring(0,10);
                                }
                                if (!TextUtils.isEmpty(m3u8)) {
                                    String homeUrl = m3u8.substring(0, m3u8.lastIndexOf("/") + 1);
                                    String m3u81 = JsoupGet.getM3u8(m3u8).get("m3u8");;
                                    if (TextUtils.isEmpty(m3u81)) {
                                        m3u8Url = m3u8;
                                    } else {
                                        String[] homeSplite = homeUrl.split("/");
                                        String[] m3u81Splites = m3u81.split("/");
                                        if (m3u81Splites[1].equals(homeSplite[3])) {
                                            m3u8Url = homeSplite[0] + "//" + homeSplite[2] + "/" + m3u81;
                                        } else {
                                            m3u8Url = homeUrl + m3u81;
                                        }
                                    }
                                    if (!TextUtils.isEmpty(m3u8Url) && m3u8Url.endsWith(".m3u8")) {
                                        List<List> tsLists = JsoupGet.getTs(m3u8Url);
                                        List<LoadingEntity> loadingEntities = (List<LoadingEntity>) preference.getObject(MyPreference.loading, LoadingEntity.class);
                                        if (loadingEntities == null) {
                                            loadingEntities = new ArrayList<>();
                                        }
                                        LoadingEntity loadingEntity = new LoadingEntity();
                                        loadingEntity.setImgUrl(imgUrl);
                                        loadingEntity.setName(GlobalStr.returnName(name));
                                        if (tsLists.size() > 0) {
                                            loadingEntity.setAllCount(tsLists.get(1).size());
                                        }else {
                                            loadingEntity.setAllCount(0);
                                            EventBus.getDefault().post(new LoadFailedEvent(name + moviePlayerEntity.getName()+" 下载失败！"));
                                            return;
                                        }
                                        loadingEntity.setSet(moviePlayerEntity.getName());
                                        loadingEntity.setUrl(m3u8Url);
                                        loadingEntities.add(loadingEntity);
                                        preference.setObject(MyPreference.loading, loadingEntities);
                                        DownThread thread = new DownThread(m3u8Url, name, moviePlayerEntity.getName(), context, imgUrl);
                                        int pos = DownTask.downThreadList.size();
                                        DownTask.downThreadList.add(pos, thread);
                                        DownTask.startDown(pos);

                                        EventBus.getDefault().post(new LoadFailedEvent("开始下载 " + name + moviePlayerEntity.getName()));
                                    }
                                }
                            }else if (isHave){
                                if (!downThread.isLoading) {
                                    int m = DownTask.downThreadList.indexOf(downThread);
                                    DownTask.startDown(m);
                                    EventBus.getDefault().post(new LoadFailedEvent("开始下载 " + name + moviePlayerEntity.getName()));
                                }else {
                                    EventBus.getDefault().post(new LoadFailedEvent("正在下载 " + name + moviePlayerEntity.getName()));
                                }
                            }else if (loadFile.exists()){
                                EventBus.getDefault().post(new LoadFailedEvent(name + moviePlayerEntity.getName()+"  已下载"));
                            }
                        }

                    }
                }).start();
                dialog.dismiss();
            }

            @Override
            public void clickCancel() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
